//
//  TripMapVC.swift
//  ImGuider X
//
//  Created by 王鹏宇 on 10/23/18.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit
import MapKit

class TripMapVC: BaseVC {

    @IBOutlet weak var mapView: MKMapView!
    
    let viewmodel:TripMapViewModel = TripMapViewModel()
    
    let manager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        DispatchQueue.main.after(0.25) {
//            
//            if let anns = self.viewmodel.anns {
//                
//                self.mapView.addAnnotations(anns)
//                
//                self.mapView.showAnnotations(anns, animated: true)
//            }
//        }
//        
        self.title = LocalizedString("trip_map")
        
        viewmodel.setupAnns()
        viewmodel.loadDataFinished = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            if let anns = self.viewmodel.anns {
                
                self.mapView.addAnnotations(anns)
                self.mapView.showAnnotations(anns, animated: true)
            }
        }
        
        LocationManager.share.startUpdatingLocation()
    }

    @IBAction func userLocationAction(_ sender: Any) {
        
        mapView.userMapCenter()
    }
    
}

extension TripMapVC: MKMapViewDelegate {
    
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        
        if let ann = annotation as? TripAnnotion {
            
            var view = mapView.dequeueReusableAnnotationView(withIdentifier: "TripAnnotionView") as? TripAnnotionView
            
            if view == nil {
                
                view = TripAnnotionView(annotation: ann, reuseIdentifier: "TripAnnotionView", anntype: .enent)
            }
            
            view?.setup(ann: ann)
            
            return view
        }
        
        return nil
    }
}
